//
//  CPSHAREController.m
//  ChinaPoem
//
//  Created by 赵俊明 on 2019/3/4.
//  Copyright © 2019 赵俊明. All rights reserved.
//

#import "CPSHAREController.h"
#import "CPHomeCell.h"
#import "CPShareDetailController.h"
#import "PYSearch.h"

@interface CPSHAREController ()<PYSearchViewControllerDelegate,UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, weak) UICollectionView *col;
@property (nonatomic, strong) CPSHAREReusableView *header;
@end

@implementation CPSHAREController
static NSString *const cID = @"cell";
static NSString *const fID = @"footer";
static NSString *const hID = @"header";

- (void)cp_rightBtn
{
    // 1.创建热门搜索
    NSMutableArray *hots = [[CPSQLTools cp_sharedInstance] cp_search:@"share" column:@"title"];
    NSString *placholder = @"输入搜索诗词名字";
    JMSelf(ws);
    PYSearchViewController *sVC = [PYSearchViewController searchViewControllerWithHotSearches:hots searchBarPlaceholder:placholder didSearchBlock:^(PYSearchViewController *searchViewController, UISearchBar *searchBar, NSString *searchText) {
        NSArray *titles = [searchText componentsSeparatedByString:@"-"];
        NSString *sql = [NSString stringWithFormat:@"select * from share where title = '%@';", titles.firstObject];
        NSMutableArray *models = [[CPSQLTools cp_sharedInstance] cp_shareData:sql];
        if (models.count > 0) {
            CPShareDetailController *shD = [[CPShareDetailController alloc] init];
            shD.model = models.firstObject;
            [searchViewController.navigationController pushViewController:shD animated:YES];
        }else{
            [ws cp_show:@"很抱歉，没有找到！" msg:@"没有找到" cancel:NO handle:^(BOOL isLive) {}];
        }
    }];
    sVC.hotSearchStyle = PYHotSearchStyleDefault; // 热门搜索风格根据选择
    sVC.searchHistoryStyle = PYHotSearchStyleDefault; // 搜索历史风格为default
    sVC.delegate = self;
    CPNavController *nav = [[CPNavController alloc] initWithRootViewController:sVC];
    [self presentViewController:nav animated:YES completion:nil];
}

#pragma mark - PYSearchViewControllerDelegate
- (void)searchViewController:(PYSearchViewController *)searchViewController searchTextDidChange:(UISearchBar *)seachBar searchText:(NSString *)searchText
{
    if (searchText.length) { // 与搜索条件再搜索
        NSString *sql = @"select * from share where title like ?";
        NSString *name = [NSString stringWithFormat:@"%%%@%%", searchText];
        searchViewController.searchSuggestions = [[CPSQLTools cp_sharedInstance] cp_searchPoem:sql likeName:name column:@"title"];
    }
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    [self cp_setupView];
    [self pullRefresh];
    self.RImage = @"search";
}

- (void)cp_setupView
{
    UICollectionViewFlowLayout *cLayout = [[UICollectionViewFlowLayout alloc] init];
    UICollectionView *col = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:cLayout];
    col.backgroundColor = [UIColor clearColor];
    col.dataSource = self;
    col.delegate = self;
    col.showsVerticalScrollIndicator = NO;
    [col registerClass:[CPHomeCell class] forCellWithReuseIdentifier:cID];
    [col registerClass:[CPSHAREReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:fID];
    [col registerClass:[CPSHAREReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:hID];
    [self.view addSubview:col];
    self.col = col;
    [col mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11.0, *)) {
            make.top.mas_equalTo(self.view.mas_safeAreaLayoutGuideTop);
            make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom);
        } else {
            make.top.mas_equalTo(self.view.mas_top);
            make.bottom.mas_equalTo(self.view.mas_bottom);
        }
        make.width.mas_equalTo(self.view);
    }];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CPHomeCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cID forIndexPath:indexPath];
    cell.model = _dataSource[indexPath.row];
    return cell;
}

#pragma mark UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    CPShareDetailController *shD = [[CPShareDetailController alloc] init];
    shD.model = _dataSource[indexPath.row];;
    [self.navigationController pushViewController:shD animated:YES];
}

#pragma mark UICollectionViewDataSource,
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _dataSource.count;
}

#pragma mark UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(kW-14, 104);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(8, 7, 5, 7);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 7;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        self.header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:hID forIndexPath:indexPath];
        if (_header == nil) {_header = [[CPSHAREReusableView alloc] init];}
        if (indexPath.section == 0) {
            CPModel *model = _dataSource.firstObject;
            NSString *content = [model.cp_content stringByReplacingOccurrencesOfString:@"\n" withString:@""];
            NSString *explanation = [model.cp_explanation stringByReplacingOccurrencesOfString:@"\n" withString:@""];
            NSString *title = [model.cp_title stringByReplacingOccurrencesOfString:@"\n" withString:@""];
            NSString *author = [model.cp_author stringByReplacingOccurrencesOfString:@"\n" withString:@""];
            _header.content.text = [NSString stringWithFormat:@"%@，%@。", content, explanation];
            _header.author.text = [NSString stringWithFormat:@"%@ / %@", title, author];
        }
        
    }else if ([kind isEqualToString:UICollectionElementKindSectionFooter]){
        _header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:fID forIndexPath:indexPath];
        if (_header == nil) {_header = [[CPSHAREReusableView alloc] init];}
    }
    return _header;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return (section == 0) ? CGSizeMake(self.view.width, 120):CGSizeMake(0, 0);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
    return CGSizeMake(0, 0);
}

#pragma mark -- 加载数据, 数据库操作
- (void)pullRefresh
{
    JMSelf(weakSelf);
    self.col.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.dataSource = [[CPSQLTools cp_sharedInstance] cp_shareRandom:50 share:YES];
        sleep(.9);
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.col reloadData];
            [weakSelf.col.mj_header endRefreshing];
        });
    }];
    [self.col.mj_header beginRefreshing];
}

@end

@implementation CPSHAREReusableView
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
        view.backgroundColor = [UIColor grayColor];
        view.alpha = 0.2;
        [self addSubview:view];
        self.view = view;
        
        UILabel *text = [[UILabel alloc] initWithFrame:CGRectZero];
        text.textAlignment = NSTextAlignmentCenter;
        text.font = kFont(17.0);
        [self addSubview:text];
        self.content = text;
        
        UILabel *author = [[UILabel alloc] initWithFrame:CGRectZero];
        author.textAlignment = NSTextAlignmentCenter;
        author.font = kFont(17.0);
        [self addSubview:author];
        self.author = author;
    }
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    _author.frame = CGRectMake(0, self.height/2-30, kW, 30);
    _content.frame = CGRectMake(0, CGRectGetMaxY(_author.frame), kW, 30);
    _view.frame = CGRectMake(15, self.height-1, self.width-30, 1);
}
@end
